// Application/Features/Menus/Queries/SearchMenus/SearchMenusQueryHandler.cs
using MediatR;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Menus.Queries.SearchMenus;

public class SearchMenusQueryHandler : IRequestHandler<SearchMenusQuery, ApiResult<PagedResult<MenuDto>>>
{
  private readonly IUnitOfWork _uow;

  public SearchMenusQueryHandler(IUnitOfWork uow) => _uow = uow;

  public async Task<ApiResult<PagedResult<MenuDto>>> Handle(SearchMenusQuery request, CancellationToken ct)
  {
    var (items, total) = await _uow.MenuRepository.GetPagedMenusAsync(
        keyword: request.Keyword,
        isActive: request.IsActive,
        pageIndex: request.PageIndex,
        pageSize: request.PageSize);

    var dto = items.Select(m => new MenuDto
    {
      Id = m.Id,
      Name = m.Name,
      Path = m.Path,
      Icon = m.Icon,
      ParentId = m.ParentId,
      Sort = m.Sort,
      IsActive = m.IsActive
    }).ToList();

    return ApiResult<PagedResult<MenuDto>>.Success(new PagedResult<MenuDto>
    {
      Items = dto,
      TotalCount = total,
      PageIndex = request.PageIndex,
      PageSize = request.PageSize
    });
  }
}